//
//  RewardsVC.m
//  夺宝吧
//
//  Created by xiaocai on 15/7/21.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "RewardsVC.h"
#import "MJRefresh.h"
#import "RewardsCell.h"
#import "RewardDetailVC.h"
#import "PdcDetailVC.h"
#import "NoDataView.h"
#define REWARDS_URL @"/api/ApiUser/getLotteryWonList"
@interface RewardsVC ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;
    //数据源
    NSMutableArray *_data;
    NSInteger _currentPage;
    //首次标志
    BOOL isFirst;
    //记录点击的cell坐标
    NSInteger _pressedCellRow;
}
@end

@implementation RewardsVC
- (void)viewWillAppear:(BOOL)animated
{
    if(_data.count > 0){
        //一个cell刷新
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:_pressedCellRow inSection:0];
        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _data = [NSMutableArray array];
    _currentPage = 1;
    _pressedCellRow = 0;
    [self loadCustomNaviBar];
    [self loadTableView];
}
- (void)setIsMyRecordFlag:(BOOL)isMyRecordFlag
{
    _isMyRecordFlag = isMyRecordFlag;
    [self startRequestForData];
}
//加载导航条
- (void)loadCustomNaviBar
{
    UIView *naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 20+44)];
    naviBar.backgroundColor = QBB_RED_COLOR;
    //返回按钮
    PublicBackBtn *backBtn = [[PublicBackBtn alloc]initWithVC:self andBackType:pop Img:[UIImage imageNamed:@"icon_back_white_press"]];
    [naviBar addSubview:backBtn];
    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 25)];
    titleLab.center = CGPointMake(WYMWITH/2, 42);
    titleLab.text = @"中奖记录";
    titleLab.font = [UIFont systemFontOfSize:TITLE_SIZE];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = [UIColor whiteColor];
    //分割线
    UILabel *fenge = [[UILabel alloc]initWithFrame:CGRectMake(0, 63.5, WYMWITH, 0.5)];
    fenge.backgroundColor = [UIColor lightGrayColor];
    [naviBar addSubview:fenge];
    [naviBar addSubview:titleLab];
    [self.view addSubview:naviBar];
}
//加载表格
- (void)loadTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WYMWITH, WYMHEIGHT - 64)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    //注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"RewardsCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [self setupRefresh];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    _currentPage = 1;
    [_data removeAllObjects];
    [self startRequestForData];
}

- (void)footerRereshing
{
    _currentPage++;
    [self startRequestForData];
}
//启动数据请求
- (void)startRequestForData
{
    [WYPublic addHudToWindow];
    NSDictionary *params = nil;
    if (self.isMyRecordFlag) {
        params = @{@"uid":[UserInfo getUserID],@"num":@"20",@"page":[NSString stringWithFormat:@"%ld",(unsigned long)_currentPage]};
    }else{
         params = @{@"uid":self.userId,@"num":@"20",@"page":[NSString stringWithFormat:@"%ld",(unsigned long)_currentPage]};
    }
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,REWARDS_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSArray *list = dic[@"data"];
        for (NSDictionary *reward in list) {
            RewardModel *model = [[RewardModel alloc]init];
            model.reward_code = reward[@"q_user_code"];
            model.reward_order_id = reward[@"recordid"];
            model.reward_share_order_score = reward[@"share_order_score"];
            model.reward_company = reward[@"company"];
            model.reward_company_code = reward[@"company_code"];
            model.reward_company_mark = reward[@"company_mark"];
            model.reward_company_money = reward[@"company_money"];
            model.reward_current_status = reward[@"current_status_desc"];
            NSNumber *g_n = reward[@"go_total"];
            model.reward_go_total = [NSString stringWithFormat:@"%ld",(unsigned long)[g_n integerValue]];
            model.reward_id = reward[@"id"];
            model.reward_imgPath = reward[@"thumb_url"];
            model.reward_is_virtual = reward[@"is_virtual"];
            model.reward_qishu = reward[@"qishu"];
            model.reward_recharge_alipay = reward[@"recharge_alipay"];
            model.reward_recharge_mobile = reward[@"recharge_mobile"];
            model.reward_recharge_qq = reward[@"recharge_qq"];
            model.reward_status = reward[@"status"];
            model.reward_time = reward[@"q_end_time"];
            model.reward_title = reward[@"title"];
            model.reward_virtual_recharge_type = reward[@"virtual_recharge_type"];
            model.reward_status_list = reward[@"status_list"];
            model.reward_current_status_value = reward[@"current_status"];
            model.reward_owner_name = reward[@"shouhuoren"];
            model.reward_address = reward[@"addr"];
            model.reward_phone = reward[@"mobile"];
            
            [_data addObject:model];
        }
        if (_data.count == 0) {
            [self addNODataView];
        }
        [_tableView reloadData];
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
        [WYPublic removeHudToWindow];
    } failedBlock:^{
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
        [WYPublic removeHudToWindow];
    } needLog:NO];
}
//没有数据默认填充的控件
- (void)addNODataView{
    NoDataView *nodateView = [[[NSBundle mainBundle]loadNibNamed:@"NoDataView" owner:self options:nil]lastObject];
    nodateView.frame = CGRectMake(0, 64, WYMWITH, nodateView.frame.size.height);
    if (self.isMyRecordFlag) {
        nodateView.isMineFlag = YES;
        nodateView.title = @"您还没有中奖记录哦!";
    }else{
        nodateView.isMineFlag = NO;
        nodateView.title = @"ta还没有中奖记录哦!";
    }
    [self.view addSubview:nodateView];
}
#pragma mark -- 表格协议函数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isMyRecordFlag) {
        return 150;
    }else{
        return 110;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RewardsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (self.isMyRecordFlag) {
        cell.isMineFlag = YES;
    }else{
        cell.isMineFlag = NO;
    }
    if (_data.count > 0) {
        RewardModel *model = _data[indexPath.row];
        [cell fillCellWithModel:model];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_data.count > 0) {
        
        RewardModel *model = _data[indexPath.row];
        //如果是他人的奖品列表，跳往商品详情
        if (_isOthersFlag) {
            //跳往商品详情
            PdcDetailVC *detailVC = [[PdcDetailVC alloc]init];
            detailVC.pdc_id = model.reward_id;
            [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:detailVC animated:YES];
            
            return;
        }
        _pressedCellRow = indexPath.row;
        //跳往奖品详情
        RewardDetailVC *detailVC = [[RewardDetailVC alloc]init];
        detailVC.isMineFlag = YES;
        detailVC.model = model;
        [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:detailVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillDisappear:(BOOL)animated
{
    [WYPublic removeHudToWindow];
}

- (void)dealloc{
    
    NSLog(@"RewardsVC dealloc");
}
@end
